<?php

namespace App\Servers\WebSocket\Abstracts;

use App\Servers\WebSocket\Interfaces\LogicInterface;
use App\Servers\WebSocket\Utils\Response;
use App\Servers\WebSocket\Utils\Tool;
use Psr\Container\ContainerInterface;
use Swoole\Coroutine;
use Swoole\Coroutine\Http\Server;

/**
 * 逻辑层的通用子类，所有逻辑层的类都需要继承该类
 */
abstract class LogicAbstract implements LogicInterface
{
    /**
     * 线程管理工具类数组，包括redis,pdo,list
     *
     * @var [type]
     */
    protected $threadTool = null;
    /**
     * socket套接字
     *
     * @var [type]
     */
    protected $fd = null; //套接字

    public function __construct(protected ContainerInterface $container)
    {
    }
    /**
     * 统一处理入口
     *
     * @param mixed $data 帧数据
     * @param array $threadTool 线程管理工具类数组
     * @param [type] $fd
     * @return mixed
     */
    public function handle(mixed $data, $fd): mixed
    {
        $this->threadTool = [
            'redis' => $this->container->get(\Swoole\Database\RedisPool::class),
            'pdo' => $this->container->get(\Swoole\Database\PDOPool::class),
            'channel' => $this->container->get(\Swoole\Coroutine\Channel::class),
            'map' => $this->container->get(\Swoole\Thread\Map::class),
        ];
        $this->fd = $fd;
        $op = $data->op;
        $lassName = static::class;
        $arr = array_reverse(Tool::splitPascalCase($lassName));
        $arr = array_map('strtolower', $arr);
        return Response::getInstance()->data($arr[0] . '-' . $arr[1], $this->$op($data->data), $op)->end();
    }
}
